package com.numbfish.ch06_message_digest.ex01_mac;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class MACCoder {
    /**
     * 初始化HmacMD5密钥
     *
     * @return byte[] 密钥
     */
    public static byte[] initHmacMD5Key() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
        // 产生密钥
        SecretKey secretKey = keyGenerator.generateKey();
        // 获得密钥
        byte[] encoded = secretKey.getEncoded();
        return encoded;
    }

    /**
     * HmacMD5消息摘要
     *
     * @param data 待做摘要处理的数据
     * @param key 密钥
     * @return byte[] 消息摘要
     * @throws Exception
     */
    public static byte[] encodeMD5Key(byte[] data,byte[] key) throws Exception {
       // 根据密钥字节数组还原密钥
        SecretKeySpec secretKey = new SecretKeySpec(key, "HmacMD5");
        // 实例化MAC
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        // 初始化MAC
        mac.init(secretKey);
        return mac.doFinal(data);
    }

    /**
     * 初始化HmacSHA256密钥
     *
     * @return byte[] 密钥
     */
    public static byte[] initHmacSHA256() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacSHA256");
        // 产生密钥
        SecretKey secretKey = keyGenerator.generateKey();
        // 获得密钥
        byte[] encoded = secretKey.getEncoded();
        return encoded;
    }

    /**
     * HmacMD5消息摘要
     *
     * @param data 待做摘要处理的数据
     * @param key 密钥
     * @return byte[] 消息摘要
     * @throws Exception
     */
    public static byte[] encodeHmacSHA256(byte[] data,byte[] key) throws Exception {
        // 根据密钥字节数组还原密钥
        SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA256");
        // 实例化MAC
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        // 初始化MAC
        mac.init(secretKey);
        return mac.doFinal(data);
    }
}
